import {
  Linking, Dimensions, Platform,
  NativeModules,
  DeviceInfo
} from 'react-native';
import moment from 'moment';
import _ from 'lodash';
import { Actions } from 'react-native-router-flux';

export const Null = () => null;
export const fromNow = (time, fixer) => {
  const isBefore = moment(time).isBefore();
  let diff = isBefore ? moment(time).toNow(true) : moment(time).fromNow(true);
  let count = diff.split(' ')[0];
  count = count === 'a' || count === 'an' ? 1 : count;
  let _prefix = '';
  let _endfix = '';
  if (fixer === 1) {
    if (isBefore) {
      _prefix = '超时 ';
    } else {
      _prefix = '剩余 ';
    }
  } else {
    if (isBefore) {
      _endfix = ' 之前';
    } else {
      _endfix = ' 之后';
    }
  }
  switch (true) {
    case /year|年/.test(diff) && fixer === 1:
      return `${_prefix}${count}年${_endfix}`;
    case /month|月/.test(diff) && fixer === 1:
      return `${_prefix}${count}月${_endfix}`;
    case /day|天/.test(diff):
      return `${_prefix}${count}天${_endfix}`;
    case /hour|小时/.test(diff):
      return `${_prefix}${count}小时${_endfix}`;
    case /minute|分钟/.test(diff):
      return `${_prefix}${count}分钟${_endfix}`;
    case /second|秒/.test(diff):
      return `${_prefix}${count}秒${_endfix}`;
    default:
      return moment(time).format('YYYY-MM-DD HH:mm:ss');
  }
};
export const age = birthday => {
  const ago = moment(birthday).fromNow(true);
  let count = ago.split(' ')[0];
  count = count === 'a' || count === 'an' ? 1 : count;
  switch (true) {
    case /year|年/.test(ago):
      return `${count}岁`;
    case /month|月/.test(ago):
      return `${count}个月`;
    case /day|天/.test(ago):
      return `${count}天`;
    default:
      return '刚出生';
  }
};
export const openURL = url => {
  return Linking.canOpenURL(url)
    .then(supported => {
      if (!supported) {
        alert('链接异常!');
      } else {
        return Linking.openURL(url);
      }
    })
    .catch(e => {
      console.error(e);
    });
};

export const idMaker = () => {
  return Math.random()
    .toString(36)
    .substr(2);
};
export const getAllData = (key, err = '获取失败') => {
  return storage.getAllDataForKey(key).then(
    data => {
      return data;
    },
    () => {
      throw new Error(err);
    }
  );
};
export const getData = (key_id, err = '获取失败') => {
  return storage.load(key_id).then(
    data => {
      return data;
    },
    () => {
      throw new Error(err);
    }
  );
};
const START_PAGE = [
  'start',
  'login',
  'loginWithPassword',
  'registe',
  'findPassword',
  'setPassword'
];
export const back2Start = () => {
  if (!_.includes(START_PAGE, Actions.currentScene)) {
    Actions.popTo('start');
  }
};

export const errorHandle = err =>
  _.flatten(
    _.map(_.values(err), ({ errors }) =>
      _.map(errors, ({ message }) => message)
    )
  );

export const addStars = (str, start, end, symbol = '*') => {
  if (!str || str.length < 1) {
    return str;
  }
  const arr = str.split('');
  return arr.map((a, i) => (i < start || i > end ? a : symbol)).join('');
};
let debounceTimer = null;
export const debounce = (fn, context, delay = 300) => {
  if (debounceTimer) {
    clearTimeout(debounceTimer);
  }
  debounceTimer = setTimeout(() => {
    fn.apply(context || null);
  }, delay + 2000);
};

// // iPhoneX
// const X_WIDTH = 375;
// const X_HEIGHT = 812;

// // screen
// const SCREEN_WIDTH = Dimensions.get('window').width;
// const SCREEN_HEIGHT = Dimensions.get('window').height;

// export function isX() {
//   return (
//     Platform.OS === 'ios' &&
//     ((SCREEN_HEIGHT === X_HEIGHT && SCREEN_WIDTH === X_WIDTH) ||
//       (SCREEN_HEIGHT === X_WIDTH && SCREEN_WIDTH === X_HEIGHT))
//   )
// }
// export function ifX (iphoneXStyle, regularStyle) {
//   if (isX()) {
//       return iphoneXStyle;
//   } else {
//       return regularStyle
//   }
// }

const X_WIDTH = 375;
const X_HEIGHT = 812;

const { height: D_HEIGHT, width: D_WIDTH } = Dimensions.get('window');

const { PlatformConstants = {} } = NativeModules;
const { minor = 0 } = PlatformConstants.reactNativeVersion || {};


export function isIphoneX () {
  if (Platform.OS === 'web') return false;
  if (minor >= 50) {
    return DeviceInfo.isIPhoneX_deprecated;
  }
  return (
    Platform.OS === 'ios' &&
    ((D_HEIGHT === X_HEIGHT && D_WIDTH === X_WIDTH) ||
      (D_HEIGHT === X_WIDTH && D_WIDTH === X_HEIGHT))
  );
}


export function genderIconProps(g) {
  switch (g) {
    case 1:
      return {name: 'mars', color: '#3399ff'};
    case 2:
      return {name: 'venus', color: '#ff6699'};
    default:
      return {name: 'question', color: '#ddd'}
  }
}

/*
这么搞没有用
const sceneStyle = {
  navigationBarStyle: {
    height: 44
  },
  titleStyle: {
    fontSize: 16,
    fontWeight: '100'
  }
};

export class MyScene extends Component {
  render() {
    return <Scene {...sceneStyle} {...this.props} />;
  }
} */
